<template>
  <div class="wrapper-list">
    <!-- 内容列表区 -->
    <div class="wrapper-table">
      <el-table
        v-loading="flagLoading"
        :data="tblDataList"
        :header-cell-style="{ 'text-align': 'center' }"
        row-key="id"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
        height="100%"
      >
        <el-table-column align="center" label="关键字词" width="200" prop="tag">
          <template #default="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.tag" size="small" />
            <span v-else>{{ scope.row.tag }}</span>
          </template>
        </el-table-column>

        <el-table-column label="权限名称" width="300" prop="label">
          <template #default="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.label" size="small" />
            <span v-else>{{ scope.row.label }}</span>
          </template>
        </el-table-column>

        <el-table-column label="权限名称" width="300" prop="code">
          <template #default="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.code" size="small" />
            <span v-else>{{ scope.row.code }}</span>
          </template>
        </el-table-column>

        <el-table-column :formatter="formatRoute" label="绑定的路由" />

        <el-table-column align="center" label="操作" width="150">
          <template #default="scope">
            <div class="wrapper-op">
              <a
                v-if="!scope.row.isEdit"
                title="绑定前端路由"
                class="ibtn ibtn-show"
                @click="onShowDialogBindRoute(scope.row.id)"
              >
                <el-icon><Paperclip /></el-icon>
              </a>
              <a v-if="!scope.row.isEdit" title="修改" class="ibtn ibtn-edit" @click="onEdit(scope.row)">
                <el-icon><Edit /></el-icon>
              </a>
              <a v-if="scope.row.isEdit" title="保存" class="ibtn ibtn-save" @click="onSave(scope.row)">
                <el-icon><Check /></el-icon>
              </a>
              <a v-if="scope.row.isEdit" title="取消" class="ibtn ibtn-cancel" @click="onCancel(scope.row)">
                <el-icon><Close /></el-icon>
              </a>
              <a v-if="!scope.row.isEdit" title="删除" class="ibtn ibtn-del" @click="onDelete(scope.row.id)">
                <el-icon><Delete /></el-icon>
              </a>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 绑定对应的前端路由 Dialog -->
    <div class="wrapper-dialog">
      <el-dialog v-model="flagDialogVisible" title="选择要绑定的前端路由" width="30%">
        <el-tree-select
          v-model="idRoute"
          :data="allRouteList"
          :props="{ value: 'id', label: 'title' }"
          :render-after-expand="false"
          :current-node-key="0"
          value-key="id"
          placeholder="选择要绑定的前端路由"
          check-strictly
        />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="flagDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onBindRoute()">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { AryToTree } from '@/utils/array'
import { toastError, toastSuccess } from '@/utils/toast'

import { ElMessageBox } from 'element-plus'

import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'PurviewListAllView',
  components: {},
  setup() {
    const tblDataList = ref([])
    const flagLoading = ref(true)
    const flagDialogVisible = ref(false)
    const idRoute = ref(0)
    const idPurview = ref(0)
    const allRouteList = ref([])
    // 当前页面是否处于编辑状态
    const flagEditing = ref(false)

    // 获取所有权限列表
    const listAllPurview = () => {
      flagLoading.value = true
      store
        .dispatch('sys_purview/listAll')
        .then((response) => {
          flagLoading.value = false
          // Array的map方法是对数组中的每个元素执行一个方法
          // 给返回的每条数据添加一个 isEdit 标识
          response.map((item) => {
            item.isEdit = false
            // return item
          })
          tblDataList.value = response
        })
        .catch((error) => {
          flagLoading.value = false
          console.log('读取权限列表数据出现错误：', error)
        })
    }
    // 获取所有前端路由列表，TreeSelect组件的数据源
    const listAllRoute = () => {
      store
        .dispatch('sys_front_route/listAll')
        .then((response) => {
          allRouteList.value = AryToTree(response, 0)
          console.log('allRouteList:', allRouteList.value)
        })
        .catch((error) => {
          console.log('得到所有前端路由数组出现错误：', error)
        })
    }
    // 格式化绑定的前端路由
    const formatRoute = (row) => {
      if (row.frontRouteList[0] && row.frontRouteList[0].title) {
        return row.frontRouteList[0].title
      } else {
        return '未绑定'
      }
    }
    // 显示绑定路由对话框
    const onShowDialogBindRoute = (idP) => {
      idPurview.value = idP
      // 根据权限id得到此权限绑定的前端路由id
      store
        .dispatch('sys_purview_route/getRouteIdByIdPurview', idP)
        .then((response) => {
          if (response) idRoute.value = response
          else idRoute.value = 1
        })
        .catch((error) => {
          console.log('根据权限id得到此权限绑定的前端路由id：', error)
        })
      flagDialogVisible.value = true
    }
    // 绑定路由
    const onBindRoute = () => {
      // 批量添加的权限有两种方式绑定前端路由
      // 1、默认绑定到id=1的根路由，此时在purview_route表里会添加一条数据
      // 此时权限绑定路由是做更新操作
      // 2、默认不在purview_route表里添加数据
      // 此时权限绑定路由是做添加操作
      // 开始是采用第2种方法，但是发现每次修改的话还要做判断，不能重复添加了
      // 因此改成第1种方法
      store
        .dispatch('sys_purview_route/modifyRouteIdByIdPurview', {
          PurviewId: idPurview.value,
          RouteId: idRoute.value,
        })
        .then(() => {
          toastSuccess('权限绑定前端路由成功！')
          listAllPurview()
        })
        .catch((error) => {
          toastError('权限绑定前端路由出现错误！')
          console.log('权限绑定前端路由出现错误：', error)
        })
      flagDialogVisible.value = false
    }
    // 按钮点击：编辑权限
    const onEdit = (row) => {
      // setSStorageObj('ParamData', row)
      // router.push({ path: 'edit' })
      // 保证只能编辑一行
      if (!flagEditing.value) {
        // 设置当前行的编辑状态为真
        row.isEdit = true
      }
      flagEditing.value = true
    }
    // 点击保存
    const onSave = (row) => {
      // 数据校验
      if (row.tag === '') {
        toastError('关键字词不能为空！')
        return false
      }
      if (row.label === '') {
        toastError('名称不能为空！')
        return false
      }
      if (row.code === '') {
        toastError('代码不能为空！')
        return false
      }
      // 更新已有数据
      updateData(row)
    }
    // 点击取消
    const onCancel = (row) => {
      // 取消编辑当前的数据
      row.isEdit = false
      // 此时可编辑其他数据
      flagEditing.value = false
    }
    // 按钮点击：删除权限
    const onDelete = (id) => {
      ElMessageBox.confirm('确定要删除此权限吗？', '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          store
            .dispatch('sys_purview/delById', id)
            .then(() => {
              toastSuccess('删除成功！')
              listAllPurview()
            })
            .catch((error) => {
              console.log('删除权限出现错误：', error)
            })
        })
        .catch(() => {})
    }
    const updateData = (purview) => {
      store
        .dispatch('sys_purview/modifyAll', purview)
        .then(() => {
          toastSuccess('修改权限数据成功！')
          flagEditing.value = false
          listAllPurview()
        })
        .catch((error) => {
          console.log('服务器修改权限数据返回错误：', error)
        })
    }

    onMounted(() => {
      listAllRoute()
      listAllPurview()
    })

    return {
      tblDataList,
      flagLoading,
      flagDialogVisible,
      idRoute,
      idPurview,
      allRouteList,
      listAllPurview,
      formatRoute,
      onShowDialogBindRoute,
      onBindRoute,
      onEdit,
      onSave,
      onCancel,
      updateData,
      onDelete,
      listAllRoute,
    }
  },
})
</script>

<style lang="scss" scoped></style>
